package it.acweb.pauseless.pauselessapp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;

public class file_utils {

	private static Context con;
	private static String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
	private static String basePath = extStorageDirectory + "/.PauselessApp/xml";
	
	public static void setContext(Context context) {
		con = context;
	}
	
	public static String getBasePath() {
		return basePath;
	}

	public static void checkExternalStorage () {
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    // We can read and write the media
		    mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    // We can only read the media
		    mExternalStorageAvailable = true;
		    mExternalStorageWriteable = false;
		} else {
		    // Something else is wrong. It may be one of many other states, but all we need
		    //  to know is we can neither read nor write
		    mExternalStorageAvailable = mExternalStorageWriteable = false;
		}		
	}
	
	public static void copy_resource () {
		System.out.println("qui ci arrivo");
		File xmlDir = new File(basePath);
		System.out.println(basePath);
		if (!xmlDir.exists()) {
			xmlDir.mkdirs();
			System.out.println("creata la directory");

			AssetManager assetManager = con.getResources().getAssets();
			/*String [] files = null;
			try {
				files = assetManager.list(".");
				System.out.println("trovati " + files.length + " files");
			} catch (Exception e) {
				System.out.println("Read raw files error");
	            e.printStackTrace();
			}*/
			
			int[] files = new int[2];
			files[0] = it.acweb.pauseless.pauselessapp.R.raw.cd_list;
			files[1] = it.acweb.pauseless.pauselessapp.R.raw.mix_list;
			
			for (int i = 0; i<files.length; i++) {
				InputStream in = null;
				OutputStream out = null;
				
				try {
					System.out.println("tento di salvare il file "+files[i]);
					//in = assetManager.open("raw/" + files[i]);
					in = con.getResources().openRawResource(files[i]);
					out = new FileOutputStream(basePath + "/" + files[i]);
					copyFile(in, out);
				} catch (Exception e) {
					System.out.println("Copy raw files error");
		            e.printStackTrace();
				}
			}
		}
	}
	
	private static void copyFile (InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
		System.out.println("copiato un file");
	}
	
}
